package com.demo1221.demo02.servlet;



import com.demo1221.demo02.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

//@WebServlet("/demo1221/demo02/login.do")
public class UserServlet extends BaseServlet {
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        Map<String, User> onlineUser = (Map<String, User>) req.getServletContext().getAttribute("onlineUser");
        if (onlineUser != null) {
            if (onlineUser.containsKey(username)) {
                req.setAttribute("msg", "用户已经登录，请勿重复登录！");
                req.getRequestDispatcher("/demo1221/demo02/login.jsp").forward(req, resp);
            }
        }
        String ip = req.getRemoteHost();
        String loginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        HttpSession session = req.getSession();
        User user = new User(username, ip, loginTime, session);
        session.setAttribute("user", user);
        resp.sendRedirect("./index.jsp");
    }

    public void quit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("user");
        req.setAttribute("msg", "退出成功！");
        req.getRequestDispatcher("/demo1221/demo02/login.jsp").forward(req,resp);
    }

    public void kick(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        User user = (User) req.getSession().getAttribute("user");
        if (user.getName().equals(username)) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("不能自己踢自己！");
            return;
        }
        Map<String, User> onlineUser = (Map<String, User>) req.getServletContext().getAttribute("onlineUser");
        if (onlineUser.containsKey(username)) {
            onlineUser.remove(username);
            req.getServletContext().setAttribute("onlineUser", onlineUser);
        }
        resp.sendRedirect("./index.jsp");
    }
}
